<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <el-form :inline="true" ref="orderPlanNolistQuery" :rules="rules" :model="orderPlanNolistQuery">
        <el-form-item prop="orderPlanNo">
          <!-- style="width: 200px;" -->
            <el-input
                clearable
                :style="{ width: inputWid(orderPlanNolistQuery.orderPlanNo) }"
                v-model="orderPlanNolistQuery.orderPlanNo"
                class="filter-item"
                placeholder="计划批号"
            ></el-input>
        </el-form-item>
        <el-form-item>
            <el-button class="filter-item" type="primary" :loading="orderPlanNoloading" v-waves @click="submitForm('orderPlanNolistQuery')">上线</el-button>
        </el-form-item>
      </el-form>
    <div class="filter-container">
        <!-- style="width: 150px;margin-right:15px;margin-top: 10px" -->
        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px;margin-top: 10px"
            :style="{ width: inputWid(param.produceNo) }"
            v-model="param.produceNo"
            placeholder="请输入产品品号"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px;margin-top: 10px"
            :style="{ width: inputWid(param.orderPlanNo) }"
            v-model="param.orderPlanNo"
            placeholder="请输入计划批号"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px;margin-top: 10px"
            :style="{ width: inputWid(param.planNo) }"
            v-model="param.planNo"
            placeholder="请输入排产序号"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="width: 150px;margin-right:15px;margin-top: 10px"
            v-model="param.sectionNo"
            placeholder="请输入工段编号"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="width: 150px;margin-right:15px;margin-top: 10px"
            v-model="param.orderType"
            placeholder="请输入工单单别"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px;margin-top: 10px"
            :style="{ width: inputWid(param.workOrderNo) }"
            v-model="param.workOrderNo"
            placeholder="请输入工单单号"
        ></el-input>

        <el-select
          clearable
          v-model="param.isOnline" 
          placeholder="请选择上线状态"
          style="margin-right: 20px;margin-top: 10px"
          >
            <el-option 
            :value="item" 
            :label="item" v-for="(item,index) in this.onlineStatus" 
            :key="index"/>
        </el-select>

        <el-select
          clearable
          v-model="param.isEnd" 
          placeholder="请选择排产状态"
          style="margin-right: 20px;margin-top: 10px"
          >
            <el-option 
            :value="item" 
            :label="item" v-for="(item,index) in this.planStatus" 
            :key="index"/>
        </el-select>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData" style="margin-top: 10px">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            style="margin-top: 10px"
            @click="cancelSubmit"
        >
        重置</el-button>
    
    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="产品品号"  prop="produceNo" align="center"/>
      <el-table-column label="排产序号"  prop="planNo" align="center"/>
      <el-table-column label="工段编号"  prop="sectionNo" align="center"/>
      <el-table-column label="工单单别"  prop="orderType" align="center"/>
      <el-table-column label="工单单号"  prop="workOrderNo" align="center"/>
      <el-table-column label="预计排产时间"  prop="estimateStartTime" align="center" width="140"/>
      <el-table-column label="工作中心"  prop="workCenter" align="center"/>
      <el-table-column label="计划排产数量"  prop="planNumber" align="center" width="100"/>
      <el-table-column label="下线数量"  prop="productionCountAll" align="center">
        <template slot-scope="scope"> 
          <div class="fx">
            {{
              scope.row.productionCountAll == -1 ? '0':scope.row.productionCountAll
            }}
           </div>
        </template>
      </el-table-column>
      <el-table-column label="合格数量"  prop="qualifiedCount" align="center">
        <template slot-scope="scope"> 
          <div class="fx">
            {{
              scope.row.qualifiedCount == -1 ? '0':scope.row.qualifiedCount
            }}
           </div>
        </template>
      </el-table-column>
      <el-table-column label="工作状态" prop="isEnd" align="center">
        <template slot-scope="scope"> 
          <div class="fx">
            {{
              scope.row.isEnd == 1? '完工': "未完工"
            }}
           </div>
        </template>
      </el-table-column>
      <el-table-column label="上线状态" prop="isOnline" align="center">
        <template slot-scope="scope"> 
          <div class="fx">
            {{
              scope.row.isOnline == 0? '未上线': "已上线"
            }}
           </div>
        </template>
      </el-table-column>
      <el-table-column label="职级约束" prop="jobClassRestrict" align="center">
        <template slot-scope="scope"> 
          <div class="fx">
            {{
              scope.row.isOnline && scope.row.jobClassRestrict == 0?'无约束'
              :scope.row.isOnline && scope.row.jobClassRestrict == 1? '有约束':''
            }}
           </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作"  align="center" width="100">
        <template slot-scope="scope" >
            <el-button size="mini" type="primary" :loading="printLoading" @click="findLinJi(scope.$index,scope.row)" v-if="scope.row.isOnline == 0">上线</el-button>
            <el-button size="mini" type="danger" :loading="printLoading" @click="offlinePlan(scope.$index,scope.row)" v-else>下线</el-button>
        </template>
      </el-table-column>
    </el-table>
   
   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- <el-divider></el-divider> -->

    <!-- <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button> -->

  </div>
</template>

<script>
import { getPlanList,planOffline,planOnline } from '@/api/planOnlineback.js'
import { planOnlineOrderPlanNo } from '@/api/CNCmachine.js'
import { findLinJi } from '@/api/productionPlan.js'
import { getCenter } from '../../api/workSection.js'
export default {
    name: 'leaderPlanOnline',
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                produceNo: '',                      //产品品号
                orderPlanNo: '',
                planNo: '',                             //排产编号
                // date: this.setMonth(),                                //日期
                sectionNo: '',                      //工段编号
                workOrderNo: '',                        //工单单号
                orderType: '',                           //工单单别
                isEnd: '未结束'
            },
            planStatus: ['未结束','已结束'],
            onlineStatus: ['未上线','已上线'],
            total: 0,  //数据的总数
            tableInfo: [],
            loadingList: false,
            loading: false,
            printLoading: false,
            orderPlanNolistQuery: {
                orderPlanNo: ''
            },
            rules: {
                orderPlanNo: [
                    { required: true, message: '计划批号不能为空！', trigger: 'blur' }
                ]
            },
            orderPlanNoloading: false
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.produceNo){ query.produceNo = this.param.produceNo}
            if(this.param.orderPlanNo){ query.orderPlanNo = this.param.orderPlanNo}
            if(this.param.planNo){ query.planNo = this.param.planNo}
            if(this.param.orderType){ query.orderType = this.param.orderType}
            if(this.param.sectionNo){ query.sectionNo = this.param.sectionNo}
            if(this.param.workOrderNo){ query.workOrderNo = this.param.workOrderNo}
            if(this.param.isOnline){ query.isOnline = this.param.isOnline == '未上线'?'0':'1'}
            if(this.param.isEnd){ query.isEnd = this.param.isEnd == '未结束'?'0':'1'}
            let data = await getPlanList(query)
            let errmsg = data.msg
            if(data.code == '1'){
                this.total = data.data.total
                this.tableInfo = data.data.records
                this.loadingList = false
            } else {
                this.$message({
                    message: errmsg,
                    type: 'warning'
                })
            }
            this.loadingList = false
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        // 查询创建的临技
        async findLinJi(index,row) {
          if(row.workCenter != 'EMS总装车间') return this.onlinesPlan(index,row)
            let query = {
                WorkOrderNo: row.workOrderNo,
                OrderType: row.orderType
            }
            const {data} = await findLinJi(query)
            console.log(data)
            if(data && data.deviceDarcodeLinJi){
              this.$confirm('该工单有临技', '注意', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.onlinesPlan(index,row)
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消'
                });          
              });
            } else {
              this.onlinesPlan(index,row)
            }
        },
        onlinesPlan(index,row){
          this.$confirm('是否确定上线?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.planOnline(index,row)
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });          
          });
        },
        async planOnline(index,row){
          this.printLoading = true
          setTimeout(() =>{
            this.printLoading = false
          },3000)
          let data = await planOnline({planId: row.planId})
          if(data.code == '2') return this.$message.error(data.msg)
          if(data.code == '1'){
            this.tableInfo[index].isOnline = 1
            this.$message.success(data.msg)
          }
        },
        offlinePlan(index,row){
          this.$confirm('是否确定下线?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.planOffline(index,row)
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });          
          });
        },
        async planOffline(index,row){
          this.printLoading = true
          setTimeout(() =>{
            this.printLoading = false
          },3000)
          let data = await planOffline({planId: row.planId})
          if(data.code == '2') return this.$message.error(data.msg)
          if(data.code == '1'){
            this.tableInfo[index].isOnline = 0
            this.$message.success(data.msg)
          }
        },
        transformDat(res) {
          const mapInfo = {
            deviceBarcode: '条码',
            scanProduceNo: '产品号',
            scanOrderType: '工单单别',
            scanWorkOrderNo: '工单单号',
            sopBarcode: 'sop号',
            scanTime: '扫码时间',
            standardManTime: '标准工时',
            planNo: '排产序号',
            isDelete: '状态'
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          if(this.param.isEnd){ query.deviceBarcode = this.param.deviceBarcode}
          if(this.param.jobNumber){ query.jobNumber = this.param.jobNumber}
          let arr = await getPlanList(query)
          const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '非数控员工扫码明细表', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach(item=>{
            let obj = {
              deviceBarcode: item.deviceBarcode,
              scanProduceNo: item.scanProduceNo,
              scanOrderType: item.scanOrderType,
              scanWorkOrderNo: item.scanWorkOrderNo,
              sopBarcode: item.sopBarcode,
              scanTime: item.scanTime,
              standardManTime: item.standardManTime,
              planNo: item.planNo,
              isDelete: item.isDelete == 0?'未删除':'已删除'
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {
                produceNo: '',                      //产品品号
                orderPlanNo: '',                    //计划批号
                planNo: '',                           //排产编号
                sectionNo: '',                      //工段编号
                workOrderNo: '',                        //工单单号
                orderType: '',                           //工单单别
                isEnd: '未结束'
            },
            this.listQuery.page = 1
            this.handleFilter()
        },
        setMonth() {
            var date = new Date()
            var year = date.getFullYear()
            var month = this.filterMonth(date.getMonth()+1)
            var day = this.filterMonth(date.getDate())
            return year + '-' + month + '-' + day
        },
        filterMonth(value) {
          if (value<10) {
            return '0' + value
          } else {
            return value
          }
        },
        //初始默认执行(重点)，返回日期格式YYYY-MM-DD HH:MM:SS
        getNowTime() {
            let dateTime = +new Date()+8*3600*1000
            const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
                .toISOString()
                .replace('T', ' ')
                .split('.')[0]
                .substring(0,10) //默认开始时间7天前
            const end = new Date(dateTime)
                .toISOString()
                .replace('T', ' ')
                .split('.')[0]
                .substring(0,10)//默认结束时间当前时间
            console.log([start, end])
            return [start, end]
        },
        // 提交表单之前先进行验证
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
            if (valid) {
                this.planOnlineOrder()
            } else {
                return false
                }
            })
        },
        async planOnlineOrder(){
            
            this.orderPlanNoloading = true

            let query = Object.assign({},this.orderPlanNolistQuery)

            let data = await planOnlineOrderPlanNo(query)

            this.orderPlanNoloading = false

            if(data.code == '2') return this.$message.error(data.msg)
            if(data.code == 1){
              this.$message.success(data.msg)
              this.resetForm('orderPlanNolistQuery')
            }
        },
        // 对整个表单输入进去清空
        resetForm(formItem) {
          this.$refs[formItem].resetFields()
        }
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

</style>